package com.itheima.reggie.filter;

import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.utils.BaseContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录权限校验过滤器
 *  1. 定义类，实现接口Filter
 *  2. 实现方法 doFilter
 *  3. 注册过滤器 ，在类上打上注解 @WebFilter("/*")
 *  4. 在springboot环境下，要想让过来器生效，需要在启动类上加上注解 @ServletComponentScan
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
       // System.out.println("=====================过滤器的线程ID：：：" + Thread.currentThread().getId());
    
        //1. 获取请求地址  http://localhost:8080/backend/index.html
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        
        //req.getRequestURL() ;   //   http://localhost:8080/backend/index.html
        String requestPath = req.getRequestURI() ;   //   /backend/index.html
        
        //2. 判断请求地址是否属于直接放行的地址
        if(requestPath.contains("login") || requestPath.contains("logout")
                ||requestPath.endsWith(".js") ||requestPath.endsWith(".css") || requestPath.contains("images")
                || requestPath.contains("element") || requestPath.contains("ico") || requestPath.contains("smscode")){
            //直接放行！
            filterChain.doFilter(servletRequest, servletResponse);
         
            return ;
        }
        
        //3. 如果不属于以上直接放行的路径，那么就要判断是否有登录。
        Employee employee = (Employee) req.getSession().getAttribute("employee");
        
        //3.1 判断是否有值
        if(employee != null){//表明已经登录过了， 直接放行！
            
            //能进入这个if语句块就表示已经登录了！ 就在这里存id值！
            BaseContext.set(employee.getId());
            
            //直接放行！
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }
        
        //4. 加上前端用户的登录判断
        User user = (User) req.getSession().getAttribute("user");
        if(user != null ){
    
    
            //能进入这个if语句块就表示已经登录了！ 就在这里存id值！
            BaseContext.set(user.getId());
            
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }
        
        if(requestPath.contains("backend")){
            //3.2 如果等于空，那么即表示没有登录，没有登录，就要跳转到登录页面去！
            resp.sendRedirect("/backend/page/login/login.html");
        }else{
            resp.sendRedirect("/front/page/login.html");
        }
        
        
    }
}
